package project;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

public class Agent2 extends Agent {

	MessageTemplate mt1 = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
			MessageTemplate.MatchSender(new AID("Agent1", AID.ISLOCALNAME)));

	protected void setup() {
		addBehaviour(new SimpleBehaviour(this) {
			public int n = 0;

			public void action() {

				while (Ag12.bool) {

					if (Ag12.ListaValori != null) {
						Ag23.ListaValoriDistincte = scoateValorileIdentice(Ag12.ListaValori);

						Ag12.ListaValori = null;
					} else {
						if (Ag12.bool != true) {
							ACLMessage msg = Ag12.mesaj;
							final ACLMessage reply;

							if (msg != null) {
								n++;
								try {
									System.out.println("AG2 - " + myAgent.getLocalName() + " <- " + msg.getContentObject());
								} catch (UnreadableException e) {
									System.out.println("Exception in Agent2");
									e.printStackTrace();
								}

								reply = msg.createReply();
								reply.setPerformative(ACLMessage.INFORM);
								try {
									reply.setContentObject((Serializable) scoateValorileIdentice((List<Data>) msg.getContentObject()));
								} catch (IOException e) {
									e.printStackTrace();
								} catch (UnreadableException e) {
									e.printStackTrace();
								}

								reply.addReceiver(new AID("Agent3", AID.ISLOCALNAME));

								Ag12.mesaj = null;
								Ag23.mesaj = reply;

								send(reply);

							} else
								block();
						}
					}
				}
			}

			@Override
			public boolean done() {
				return false;
			}

		});

	}

	private static List<Data> scoateValorileIdentice(List<Data> datas) {

		List<Data> result = new ArrayList<Data>();
		int lastValue = -1;

		for (Data data : datas) {
			if (data.getValue() != lastValue) {
				result.add(data);
			}
			lastValue = data.getValue();
		}
		return result;
	}

}
